import React, { FC } from 'react';
import { Form, Input, Select } from 'antd';
import { FormComponentProps } from 'antd/lib/form';
import CommonModal from '@/components/Modal/CommonModal';
import { ModalStatus } from '@/constants/common';
import { validatePhone } from '@/utils/validator';
import {
  IDepartmentItem,
  ICreateUserParams,
  IUserListItem,
  IRoleItem,
} from '@/services/manageUser';

const FormItem = Form.Item;
const { Option } = Select;

const FormItemLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 19 },
};

interface IUserModalProps extends FormComponentProps {
  loading: boolean;
  status: ModalStatus;
  selectedItem: Partial<IUserListItem>;
  filterOpts: Array<IDepartmentItem>;
  allRoles: Array<IRoleItem>;
  hideModal: () => void;
  createItem: (params: ICreateUserParams) => Promise<any>;
  updateItem: (params: ICreateUserParams) => Promise<any>;
  refreshList?: () => void;
  setItemInfo: (params: IUserListItem) => void;
}

const UserModal: FC<IUserModalProps> = props => {
  const {
    status,
    hideModal,
    form,
    createItem,
    updateItem,
    refreshList,
    setItemInfo,
    selectedItem,
    allRoles,
    filterOpts,
    loading,
  } = props;
  const { getFieldDecorator } = form;

  const doConfirm = () => {
    form.validateFields((err, values) => {
      if (!err) {
        if (status === ModalStatus.Create) {
          setItemInfo({ ...values });
          createItem(values).then(() => {
            hideModal();
            refreshList && refreshList();
          });
        } else {
          setItemInfo({ ...selectedItem, ...values });

          updateItem({ adminUserCode: selectedItem.userCode, ...values }).then(() => {
            hideModal();
            refreshList && refreshList();
          });
        }
      }
    });
  };

  return (
    <CommonModal
      visible={status === ModalStatus.Edit || status === ModalStatus.Create}
      title={status === ModalStatus.Create ? '新增用户' : '修改用户'}
      btnOkText={status === ModalStatus.Create ? '确定' : '保存'}
      onCancel={hideModal}
      onOk={doConfirm}
      loading={loading}
    >
      <Form {...FormItemLayout} colon={false}>
        <FormItem label="姓名">
          {getFieldDecorator('name', {
            rules: [{ required: true, message: '请输入项目名称' }],
          })(<Input placeholder="请输入姓名" />)}
        </FormItem>
        <FormItem label="手机号">
          {getFieldDecorator('phone', {
            rules: [
              { required: true, message: '请输入手机号' },
              {
                validator: validatePhone,
              },
            ],
          })(<Input placeholder="请输入手机号" disabled={status === ModalStatus.Edit} />)}
        </FormItem>
        <FormItem label="所属项目">
          {getFieldDecorator('orgId', {
            rules: [{ required: true, message: '请输入所属项目' }],
          })(
            <Select placeholder="请选择">
              {filterOpts.map(department => {
                return (
                  <Option value={department.id} key={department.id}>
                    {department.name}
                  </Option>
                );
              })}
            </Select>,
          )}
        </FormItem>
        <FormItem label="关联角色">
          {getFieldDecorator('roleIds', {
            rules: [{ required: true, message: '请选择关联角色' }],
          })(
            <Select showSearch mode="multiple" placeholder="请选择" optionFilterProp="children">
              {allRoles.map((role: IRoleItem) => {
                return (
                  <Option value={role.id} key={role.id}>
                    {role.roleName}
                  </Option>
                );
              })}
            </Select>,
          )}
        </FormItem>
      </Form>
    </CommonModal>
  );
};

const WrappedUserModal = Form.create<IUserModalProps>({
  mapPropsToFields(props) {
    const { selectedItem } = props;

    return {
      name: Form.createFormField({
        value: selectedItem.name || '',
      }),
      phone: Form.createFormField({
        value: selectedItem.phone,
      }),
      roleIds: Form.createFormField({
        value: selectedItem.roleIds,
      }),
      orgId: Form.createFormField({
        value: selectedItem.orgId,
      }),
    };
  },
})(UserModal);

export default WrappedUserModal;
